﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ExpressionHelper.cs" company="XamlNinja">
//   2011 Richard Griffin and Ollie Riches
// </copyright>
// <summary>
//   Expression helper - helper methods for use with expression types.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace WP7Contrib.Common.Helpers
{
    using System;
    using System.Linq.Expressions;

    /// <summary>
    /// Expression helper class.
    /// </summary>
    public static class ExpressionHelper
    {
        /// <summary>
        /// Extracts the name associated with an Expression.
        /// </summary>
        /// <param name="expression">
        /// The expression to be evaluated.
        /// </param>
        /// <typeparam name="T">The function type for the expression.
        /// </typeparam>
        /// <returns>
        /// Returns the expression name.
        /// </returns>
        public static string ExpressionName<T>(Expression<Func<T>> expression)
        {
            var lambda = expression as LambdaExpression;
            MemberExpression memberExpression;
            if (lambda.Body is UnaryExpression)
            {
                var unaryExpression = (UnaryExpression)lambda.Body;
                memberExpression = (MemberExpression)unaryExpression.Operand;
            }
            else
            {
                memberExpression = (MemberExpression)lambda.Body;
            }

            return memberExpression.Member.Name;
        }
    }
}
